package com.rockcent.mall.lib;

import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.UserInfo;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.UserInfoRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by oyhk on 15/11/29.
 * 自动登录过滤器
 */
public class AutoLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private BaseUserHelper userHelper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoRepository userInfoRepository;

    private String userToken;

    public AutoLoginInterceptor(String userToken) {
        this.userToken = userToken;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 当userToken 等于空,session需要设置为空
        String userToken = RequestUtils.getCookie(this.userToken, request);
        if (StringUtils.isBlank(userToken)) {
            userToken = request.getHeader(this.userToken);
        }
        if (StringUtils.isBlank(userToken)) {
            userHelper.setSession(null, request);
            return true;
        }
        UserInfoDto userBase = userHelper.getSession(request);
        if (userBase != null) {
            return true;
        }


        String userInfoId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken).get();
        if (StringUtils.isBlank(userInfoId)) {
            return true;
        }
        UserInfo userInfo = userInfoRepository.findOne(Long.valueOf(userInfoId));
        if (userInfo == null) {
            return true;
        }
        // 设置登录的session
        userHelper.setSession(userInfo, request);
        return super.preHandle(request, response, handler);
    }
}
